// miniprogram/pages/index/index.js
const db = wx.cloud.database()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [
      'https://img.zcool.cn/community/015a435e25a8e2a80120a89548c631.jpg@1280w_1l_2o_100sh.jpg',
      'https://img.zcool.cn/community/01112c5e25a8dca801216518521a78.jpg@1280w_1l_2o_100sh.jpg',
      'https://img.zcool.cn/community/014a385e25a8d9a80120a8959a000d.jpg@1280w_1l_2o_100sh.jpg'
    ],
    listDta: [],
    current: 'links'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getListData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  handleLinks(e) {
    let id = e.target.dataset.id;
    wx.cloud.callFunction({
      name: 'update',
      data: {
        collection: 'watermelon',
        doc: id,
        data: "{links: _.inc(1)}"
      }
    }).then((res) => {
      let updated = res.result.stats.updated
      if (updated) {
        let cloneListData = [...this.data.listDta]
        for (let i = 0; i < cloneListData.length; i++) {
          if (cloneListData[i]._id == id) {
            cloneListData[i].links++
          }
        }
        this.setData({
          listDta: cloneListData
        })
      }
    })
  },
  handleCurrent(e) {
    let current = e.target.dataset.current
    if (current == this.data.current) {
      return false
    }
    this.setData({
      current
    }, () => {
      this.getListData()
    })
  },
  getListData() {
    db.collection("watermelon")
    .field({
      userPhoto: true,
      nickName: true,
      links: true
    })
    .orderBy(this.data.current, 'desc')
    .get()
    .then((res) => {
      this.setData({
        listDta: res.data
      })
    })
  },
  handleDetail(e) {
    let id = e.target.dataset.id;
    console.log(id)
    wx.navigateTo({
      url: '/pages/detail/detail?userId=' + id
    })
  }
})